import React, { Component } from "react";
import userModel from "../model/userModel";

export default class User extends Component {
  constructor(props) {
    super(props);
    this.state = {
      list: [],
      username: "",
      userpwd: "",
    };
  }
  async componentDidMount() {
    let { data } = await userModel.query({});
    this.setState({
      list: data,
    });
  }
  delById = async (id) => {
    //数据  页面
    await userModel.del(id);
    this.setState({
      list: this.state.list.filter((item) => item.id !== id),
    });
  };

  add = async () => {
    let { data: list } = await userModel.query({
      username: this.state.username,
    });
    if (list.length) {
      alert("改用户名已经存在");
    } else {
      let { data } = await userModel.add({
        username: this.state.username,
        userpwd: this.state.userpwd,
      });
      this.setState({
        list: [...this.state.list, data],
      });
    }
  };

  render() {
    // if(!this.state.list.length) console.log("1")
    // else console.log("2")
    return (
      <div className="user">
        <div className="add">
          <div>
            用户名
            <input
              value={this.state.username}
              onChange={(e) => {
                this.setState({
                  username: e.target.value,
                });
              }}
            />{" "}
          </div>
          <div>
            密码{" "}
            <input
              value={this.state.userpwd}
              onChange={(e) => {
                this.setState({
                  userpwd: e.target.value,
                });
              }}
            />{" "}
          </div>
          <div>
            <button
              onClick={() => {
                this.add();
              }}
            >
              新增
            </button>
          </div>
        </div>

        <div className="table">
          <div className="tr">
            <div className="td">编号</div>
            <div className="td">用户名</div>
            <div className="td">密码</div>
            <div className="td">操作</div>
          </div>
          {this.state.list.map((item) => (
            <div className="tr" key={item.id}>
              <div className="td">{item.id}</div>
              <div className="td">{item.username}</div>
              <div className="td">{item.userpwd}</div>
              <div
                className="td"
                onClick={() => {
                  this.delById(item.id);
                }}
              >
                删除
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  }
}
